const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;

//src\compile\generate.js
// 解析ast中元素的属性
function genAttr(attrs) {
  let _attrs = {};
  attrs.forEach((item) => {
    if (item.name !== "style") {
      _attrs[item.name.trim()] = item.value.trim();
    } else {
      let temp = {};
      item.value.split(";").map((style) => {
        let [key, value] = style.split(":");
        if (value) {
          temp[key.trim()] = value.trim();
        }
      });
      _attrs["style"] = temp;
    }
  });
  return Object.keys(_attrs).length === 0 ? null : JSON.stringify(_attrs);
}

//src\compile\generate.js
// 解析ast中的文本
function genChild(children) {
  let str = "";
  // console.log(children);
  if (children.length) {
    children.forEach((child) => {
      str += gen(child);
    });
  } else {
    // str = '_v()'
  }
  return str;
}

function gen(ast) {
  let str = ",_v(";
  let match;
  if (ast.type === 1) {
    // 元素
    return `,${generate(ast)}`;
  } else {
    // {{}}判断文本是否包含
    if (defaultTagRE.test(ast.text)) {
      let lastIndex = (defaultTagRE.lastIndex = 0); // 正则从0重新开始匹配
      // 循环查找{{}}
      while ((match = defaultTagRE.exec(ast.text))) {
        // 判断{{}}之前是否有字符串
        if (match.index > lastIndex) {
          // 截取{{}}之前的字符串
          str += `"${ast.text.slice(lastIndex, match.index)}"+`;
        }
        lastIndex = match.index + match[0].length;
        // 获取{{}}中的字符串
        str += `_s(${match[1].trim()})+`;
      }

      // 判断最后一个{{}}后面是否有字符串,有就截取拼接
      // console.log(defaultTagRE.lastIndex)
      if (lastIndex < ast.text.length) {
        str += `"${ast.text.slice(lastIndex, ast.text.length)}"+`;
      }
    } else {
      // 没有{{}}直接拼接
      str += `"${ast.text}"+`;
    }
    str = str.slice(0, -1); //过滤最后的+
  }
  return (str += ")");
}

export function generate(ast) {
  let attrs = genAttr(ast.attrs) || undefined;
  let renderStr = `_c("${ast.tag}",${attrs}${genChild(ast.childrens)})`;
  return renderStr;
}
